package org.apache.shiro;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author fangtongle
 * @version 1.0
 * @description Shiro JDBCRealm
 * @date 2018/4/19
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class shiro_05 {

    DruidDataSource dataSource = new DruidDataSource();

    {
        dataSource.setUrl("jdbc:mysql://localhost:3306/demo");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
    }

    @Test
    public void contextLoads() {

        JdbcRealm jdbcRealm = new JdbcRealm();
        jdbcRealm.setDataSource(dataSource);
        jdbcRealm.setPermissionsLookupEnabled(true);

        String sql01 = "select password from test_users where username = ?";
        jdbcRealm.setAuthenticationQuery(sql01);

        String sql02 = "select role_name from test_user_role where user_name = ?";
        jdbcRealm.setUserRolesQuery(sql02);

        String sql03 = "select permission from test_roles_permissions where role_name = ?";
        jdbcRealm.setPermissionsQuery(sql03);
        // 1. 构建SecurityManager环境
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        securityManager.setRealm(jdbcRealm);

        // 2. 主体认证授权来提交请求
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("fangtongle", "admin");
        subject.login(token);

        System.out.println("isAuthenticated: " + subject.isAuthenticated());

        subject.checkRoles("user");
        subject.checkPermission("user:update");
        subject.logout();
        System.out.println("isAuthenticated: " + subject.isAuthenticated());
    }

}
